using System;
using System.Collections.Generic;
using System.Text;
using System.Web.UI.WebControls;
using System.Web.Security;
using CMS.BIZ;
using CMS.BOP;

namespace CMS.Web.UI.UserControls
{
    public class RoleManager : UserControl
    {
        protected ListBox lbMembershipUser;
        protected ListBox lbRole;
        protected Button bValidate;

        public RoleManager()
        {
            base.Init += new EventHandler(RoleManager_Init);
        }

        void RoleManager_Init(object sender, EventArgs e)
        {
            lbMembershipUser.SelectedIndexChanged += new EventHandler(MembershipUser_SelectedIndexChanged);
            bValidate.Click += new EventHandler(Validate_Click);
            lbRole.SelectionMode = ListSelectionMode.Multiple;
            SetFieldsValue();
        }

        private void SetFieldsValue()
        {
            List<string> users = ((SqlBizMembershipProvider)Membership.Provider).GetAllUserNames(true,false);
            string[] roles = Roles.GetAllRoles();
            foreach (string user in users)
            {
                lbMembershipUser.Items.Add(user);
            }
            foreach (string role in roles)
            {
                lbRole.Items.Add(role);
            }
        }

        void Validate_Click(object sender, EventArgs e)
        {
            string selectedUser = lbMembershipUser.SelectedValue;
            if (selectedUser == null) return;
            List<string> userIn = new List<string>();
            List<string> userOut = new List<string>();
            foreach (ListItem item in lbRole.Items)
            {
                if (item.Selected)
                {
                    if(!Roles.IsUserInRole(selectedUser,item.Value)) userIn.Add(item.Value);
                }
                else
                {
                    if (Roles.IsUserInRole(selectedUser, item.Value)) userOut.Add(item.Value);
                }
            }
            if(userOut.Count > 0) Roles.RemoveUserFromRoles(selectedUser, userOut.ToArray());
            if(userIn.Count > 0) Roles.AddUserToRoles(selectedUser, userIn.ToArray());
        }

        void MembershipUser_SelectedIndexChanged(object sender, EventArgs e)
        {
            string selectedUser = lbMembershipUser.SelectedValue;
            string[] roles = Roles.GetRolesForUser(selectedUser);
            lbRole.SelectedIndex = -1;
            foreach (string role in roles)
            {
                ListItem item = lbRole.Items.FindByValue(role);
                if(item != null) item.Selected = true;
            }
        }

    }
}
